package youleche.com.controler.servlet;

import java.beans.IntrospectionException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import youleche.com.business.BBaseParamInfo;
import youleche.com.caches.BaseParamInfoCache;
import youleche.com.caches.CacheFactory;
import youleche.com.controler.servlet.common.UlecheHttpServlet;
import youleche.com.factory.MLLogFactory;
import youleche.com.model.MBaseParamInfo;
import youleche.com.util.DateUtil;
import youleche.com.util.JsonHelper;

/**
 * Servlet implementation class SBaseParamInfoServlet
 */
public class SBaseParamInfoServlet extends UlecheHttpServlet {
	private static final long serialVersionUID = 1L;
	
   /**
    * 构造器
    */
    public SBaseParamInfoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int action = Integer.parseInt(request.getParameter("action"));
		switch(action){
			case 0:
				///添加基础参数类别
				this.addBaseInfoForType(request, response);
				break;
			case 1:
				//判断类别是否存在
				this.isExistBaseInfo(request, response);
				break;
			case 2:
				//判断菜单是否存在
				this.isExistMenu(request, response);
				break;
			case 3:
				///添加基础参数
				this.addBaseInfoNo(request, response);
				break;
			case 4:
				///添加基础参数(判重复)
				this.addBaseInfo(request, response);
				break;
			case 5:
				///得到邮件模板
				this.getEmailModule(request, response);
				break;
				
		}
	}
	
	/**
	 * 得到邮件模板
	 * @param request 请求
	 * @param response 响应
	 */
	@SuppressWarnings({ "static-access", "unchecked" })
	private void getEmailModule(HttpServletRequest request, HttpServletResponse response){
		try {
			List<MBaseParamInfo> list = (List<MBaseParamInfo>) CacheFactory.getBaseParamInfoCache().getCache();
			if(list != null && list.size() > 0){
				for (MBaseParamInfo info : list) {
					if("邮件模板".equals(info.getParamName())){
						Gson gson = new Gson();
						super.response(response, gson.toJson(info));
						return;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "");
		}
		
		super.response(response, "");
	}
	/**
	 * 判断是否存在基础参数信息
	 * @param request 请求
	 * @param response 响应
	 */
	@SuppressWarnings({ "static-access", "unchecked" })
	private void isExistMenu(HttpServletRequest request, HttpServletResponse response){
		try {
			String result = "0";
			List<MBaseParamInfo> list = (List<MBaseParamInfo>) CacheFactory.getBaseParamInfoCache().getCache();
			String value = request.getParameter("menu");
			String type = request.getParameter("type");
			for (MBaseParamInfo param : list) {
				if(type.equals(param.getParamName()) && value.equals(param.getParamValue())){
					result = "1";
					break;
				}
			}
			
			super.response(response, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 判断是否存在基础参数信息
	 * @param request 请求
	 * @param response 响应
	 */
	@SuppressWarnings({ "static-access", "unchecked" })
	private void isExistBaseInfo(HttpServletRequest request, HttpServletResponse response){
		try {
			String result = "0";
			List<MBaseParamInfo> list = (List<MBaseParamInfo>) CacheFactory.getBaseParamInfoCache().getCache();
			String value = request.getParameter("value");
			for (MBaseParamInfo param : list) {
				if("类别".equals(param.getParamName()) && value.equals(param.getParamValue())){
					result = "1";
					break;
				}
			}
			if(value.length() <= 4){
				result = "3";
			}else{
				value = value.substring(value.length() - 4, value.length());
				if(!"Menu".equals(value)){
					result = "2";
				}
			}
			
			super.response(response, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 添加基础参数
	 * @param request 请求
	 * @param response 响应
	 */
	@SuppressWarnings("static-access")
	private void addBaseInfo(HttpServletRequest request, HttpServletResponse response){
		try {
			MBaseParamInfo baseInfo = (MBaseParamInfo)JsonHelper.getObjectByJsonString(request, MBaseParamInfo.class);

			BBaseParamInfo handler = new BBaseParamInfo();
			if(this.isExistSameParamName(baseInfo.getParamName())){
				//更新邮件模板
				MBaseParamInfo updateBaseInfo = this.getBaseInfoByParamName(baseInfo.getParamName());
				updateBaseInfo.setParamValue(baseInfo.getParamValue());
				handler.updateBaseInfobyKeyId(updateBaseInfo);
				CacheFactory.getBaseParamInfoCache().updateCache();
				super.response(response, "3");
				return;
			}
			
			if("".equals(baseInfo.getAssociatedKeyID()) || null == baseInfo.getAssociatedKeyID()){
				baseInfo.setAssociatedKeyID("000000");				
			}
			
			baseInfo.setAddTime(DateUtil.getNowDate());
			
			if(handler.addBaseParamInfo(baseInfo) > 0){
				CacheFactory.getBaseParamInfoCache().updateCache();
				super.response(response, "1");
				return;
			}else{
				super.response(response, "0");
			}
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "0");
		} 
	}
	
	/**
	 * 根据参数名获取参数信息，该参数有且仅有一个
	 * @param paramName 参数名
	 * @return 返回参数信息
	 */
	@SuppressWarnings({ "static-access", "unchecked" })
	private MBaseParamInfo getBaseInfoByParamName(String paramName){
		List<MBaseParamInfo> list = null;
		try {
			list = (List<MBaseParamInfo>) CacheFactory.getBaseParamInfoCache().getCache();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(list == null || list.size() < 1){
			return null;
		}
		
		for (MBaseParamInfo base : list) {
			if(base.getParamName().equals(paramName)){
				return base;
			}
		}
		
		return null;
	}
	
	/**
	 * 更新基础参数
	 * @param info 基础参数信息
	 * @param request request请求
	 */
	private void updateBaseInfo(MBaseParamInfo info, HttpServletRequest request){
		BBaseParamInfo handler = new BBaseParamInfo();
		try {
			handler.updateBaseInfobyKeyId(info);
		} catch (Exception e) {			
			MLLogFactory.exceptionLog("更新基础参数失败", "更新基础参数失败", e.getMessage(), request.getRemoteAddr());
		}
	}
	
	/**
	 * 是否存在相同的基础参数
	 * @param paramName 参数名
	 * @return 返回bool值  true-是
	 */
	private boolean isExistSameParamName(String paramName){
		try {
			List<MBaseParamInfo> list = (List<MBaseParamInfo>) CacheFactory.getBaseParamInfoCache().getCache();
			if(list != null && list.size() > 0){
				for (MBaseParamInfo info : list) {
					if(paramName.equals(info.getParamName())){
						return true;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return true;
		}
		
		return false;
	}
	
	/**
	 * 添加基础参数
	 * @param request 请求
	 * @param response 响应
	 */
	@SuppressWarnings("static-access")
	private void addBaseInfoNo(HttpServletRequest request, HttpServletResponse response){
		try {
			MBaseParamInfo baseInfo = (MBaseParamInfo)JsonHelper.getObjectByJsonString(request, MBaseParamInfo.class);
			BBaseParamInfo handler = new BBaseParamInfo();
			if("".equals(baseInfo.getAssociatedKeyID()) || null == baseInfo.getAssociatedKeyID()){
				baseInfo.setAssociatedKeyID("000000");				
			}else{
				baseInfo.setParamName(this.getBaseParamByKeyId(baseInfo.getAssociatedKeyID()).getParamName());
			}
			
			baseInfo.setAddTime(DateUtil.getNowDate());
			if(handler.addBaseParamInfo(baseInfo) > 0){
				CacheFactory.getBaseParamInfoCache().updateCache();
				super.response(response, "");
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (IntrospectionException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据keyId获取基础参数
	 * @param keyId
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "static-access" })
	private MBaseParamInfo getBaseParamByKeyId(String keyId){
		List<MBaseParamInfo> list = null;
		try {
			list = (List<MBaseParamInfo>) CacheFactory.getBaseParamInfoCache().getCache();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(list == null || list.size() < 1){
			return null;
		}
		
		for (MBaseParamInfo base : list) {
			if(base.getKeyID().equals(keyId)){
				return base;
			}
		}
		
		return null;
	}
	
	/**
	 * 添加基础参数
	 * @param request 请求
	 * @param response 响应
	 */
	@SuppressWarnings("static-access")
	private void addBaseInfoForType(HttpServletRequest request, HttpServletResponse response){
		try {
			MBaseParamInfo baseInfo = (MBaseParamInfo)JsonHelper.getObjectByJsonString(request, MBaseParamInfo.class);
			BBaseParamInfo handler = new BBaseParamInfo();
			baseInfo.setAssociatedKeyID("000000");
			baseInfo.setAddTime(DateUtil.getNowDate());
			baseInfo.setParamName("类别");
			if(handler.addBaseParamInfo(baseInfo) > 0){
				CacheFactory.getBaseParamInfoCache().updateCache();
				super.response(response, "");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
